using System.IO;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace DA.AnimGraph.Editor {
    public static class AnimGraphAssetsUtility {

        #region Setting

        public const string settingPath = "ProjectSettings/AnimGraphEditorSetting.asset";

        public static AGEditorSettingObject LoadEditorSetting() {
            AGEditorSettingObject settingObject;
            var files = InternalEditorUtility.LoadSerializedFileAndForget(settingPath);
            if (files.Length == 0) {
                settingObject = ScriptableObject.CreateInstance<AGEditorSettingObject>();
                SaveEditorSetting(settingObject);
            } else {
                settingObject = files[0] as AGEditorSettingObject;
            }
            return settingObject;
        }

        public static void SaveEditorSetting(AGEditorSettingObject settingObject) {
            if (settingObject != null) {
                EditorUtility.SetDirty(settingObject);
                InternalEditorUtility.SaveToSerializedFileAndForget(new[] { settingObject }, settingPath, true);
            }
        }

        #endregion


        public static string OpenSaveDialog() {
            var path = EditorUtility.SaveFilePanelInProject("save anim graph asset", "NewAnimGraph", "asset", "");
            if (!path.EndsWith(".aga.asset")) {
                path = Path.ChangeExtension(path, ".aga.asset");
            }
            return path;
        }

        public static string OpenLoadDialog() {
            var path = EditorUtility.OpenFilePanel("open anim graph asset", "", "asset");
            return path;
        }

        public static string SelectPublishFolder(string defaultPath = "Assets") {
            string folderPath = EditorUtility.SaveFolderPanel("Select Folder", defaultPath, "");
            string assetsPath = Application.dataPath;
            var path = folderPath.Substring(assetsPath.Length - "Assets".Length);
            path += "/";
            return path;
        }

        /// <summary>
        /// 创建新的空文件
        /// </summary>
        [MenuItem("Assets/Create/AnimGraph")]
        public static void CreateAssetByMenu() {
            var assetHandle = NewAnimGraph();
            assetHandle.ReloadSOUuid();

            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
            if (string.IsNullOrEmpty(path)) {
                path = "Assets";
            } else if (Path.HasExtension(path)) {
                path = Path.GetDirectoryName(path);
            }

            // 防止文件名重复
            var defaultName = "new_anim_graph";
            var savePath = $"{path}/{defaultName}.aga.asset";
            int number = 0;
            while (File.Exists(savePath)) {
                number++;
                savePath = $"{path}/{defaultName} ({number}).aga.asset";
            }

            assetHandle.savePath = savePath;
            assetHandle.Save();
        }

        /// <summary>
        /// 创建指定文件名的AG
        /// 用于后续自定义内容，所以没有默认graph
        /// 导出路径设定为同目录了
        /// </summary>
        /// <param name="path">"Assets"开始的路径</param>
        /// <param name="fileName">文件名，不包括"aga"</param>
        /// <returns></returns>
        internal static AGAAssetHandle CreateAssetByNameForEdit(string path, string fileName) {
            var assetHandle = AGAAssetHandle.Create();
            assetHandle.ReloadSOUuid(); // 自定义内容时，如果创建了graph需要再调用一次这个

            // 防止文件名重复
            var savePath = $"{path}/{fileName}.aga.asset";
            int number = 0;
            while (File.Exists(savePath)) {
                number++;
                savePath = $"{path}/{fileName} ({number}).aga.asset";
            }

            assetHandle.savePath = savePath;
            assetHandle.publishPath = path;
            // assetHandle.Save(); // 外部用完记得保存
            return assetHandle;
        }

        internal static AGAAssetHandle NewAnimGraph() {
            var assetHandle = AGAAssetHandle.Create();
            var dataRootHandle = assetHandle.GetRootHandle(null, null);
            var graphHandle = dataRootHandle.NewGraph("root");
            // var subGraphHandle = graphHandle.NewSubGraph();//放到NewGraph()里处理了
            // subGraphHandle.AddResultNode();
            return assetHandle;
        }
    }
}